package 热题100;
//2. 两数相加
public class Num2_addTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);//头结点
        ListNode cur = pre;//前驱，尾插

        int carry = 0;//用来表示是否有进位

        //只要有一个链表不为空，就一直执行，为空的链表用 0代替相加
        while(l1 != null || l2 != null){
            int x1 = l1 == null ? 0 : l1.val;
            int x2 = l2 == null ? 0 : l2.val;

            int sum = x1 + x2 + carry;

            carry = sum / 10;
            sum %= 10;

            cur.next = new ListNode(sum);
            cur = cur.next;

            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;

        }
        if(carry > 0) cur.next = new ListNode(carry);

        return pre.next;
    }
}
